/*******************************************************************************
 * Package: com.hngtrust.iir.user.controller
 * Type:    TagRelController
 * Date:    2021/3/22 14:43
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.user.controller;

import cn.hutool.json.JSONObject;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.controller.vo.OptLogReqVO;
import com.hngtrust.iir.base.service.LogService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.elk.service.ElkService;
import com.hngtrust.iir.user.controller.dto.LabelReqVO;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.user.service.TagService;
import com.hngtrust.iir.util.ElkUtils;
import com.tiger.util.MyHttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义标签管理
 *
 * @author Keqiwei
 * @date 2021/3/22 14:43
 */
@Slf4j
@Api(tags = "自定义标签管理")
@RestController
@RequestMapping("/tag-rel")
public class TagRelController {
    @Autowired
    private TagRelService tagRelService;
    
    @Autowired
    private ElkService elkService;
    
    @Autowired
    private TagService tagService;
    
    @Value("${elk.search.indexname.news}")
    private String news;
    
    
    @Value("${elk.search.indexname.report}")
    private String report;
    
    @Value("${elk.search.indexname.notice}")
    private String notice;
    
    @Value("${elk.search.url}")
    private String url;
    
    @Value("${elk.search.indexname.point}")
    private String point;
    
    @Autowired
    private LogService logService;
    
    //文件路径
    @Value("${elk.search.url}")
    private String elkUrl;
    
    @Value(("${elk.search.indexname.private-report}"))
    private String indexName;
    
    @Autowired
    private MyIdGenerator myIdGenerator;
    @ApiOperation("添加自义定标签")
    @PostMapping("/add-label")
    public ResponseInfo<Object> addLabel(@ApiParam("标签参数") @Valid @RequestBody List<LabelReqVO> vo){
        List<LabelReqVO> voList = vo.stream().filter(v -> {
            if (Constant.DEFAULT_STATUS_NORMAL.equals(v.getStatus())) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        
        
        List<String> tags = voList.stream().map(t -> t.getTagName()).collect(Collectors.toList());
        if (Constant.TAG_DATATYPE_NEWS.equals(vo.get(0).getDataType())){
            String elkId = tagService.getElkId(news, vo.get(0).getDataId());
            if (null == elkId){
                log.error("获取elkid失败");
            }else {
                log.info("修改新闻id"+vo.get(0).getDataId()+"elkID"+elkId);
                elkService.updateNewsInfoTags(elkId,new HashSet<>(tags));
            }
            
        }else if (Constant.TAG_DATATYPE_REPORT.equals(vo.get(0).getDataType())){
            String elkId = tagService.getElkId(report, vo.get(0).getDataId());
            if (null == elkId){
                log.error("获取elkid失败");
            }else {
                log.info("修改研报id"+vo.get(0).getDataId()+"elkID"+elkId);
                elkService.updateReportTags(elkId,new HashSet<>(tags));
            }
            
        }else if (Constant.TAG_DATATYPE_NOTICE.equals(vo.get(0).getDataType())){
            String elkId = tagService.getElkId(notice, vo.get(0).getDataId());
            if (null == elkId){
                log.error("获取elkid失败");
            }else {
                log.info("修改公告id"+vo.get(0).getDataId()+"elkID"+elkId);
                elkService.updateNoticeTags(elkId,new HashSet<>(tags));
            }
            
        }else if (Constant.TAG_DATATYPE_POINT.equals(vo.get(0).getDataType())){
            String elkId = tagService.getElkId(point, vo.get(0).getDataId());
            if (null == elkId){
                log.error("获取elkid失败");
            }else {
                log.info("修改专家观点id"+vo.get(0).getDataId()+"elkID"+elkId);
                elkService.updatePointTags(elkId,new HashSet<>(tags));
            }

        }else {
            OptLogReqVO vo1 = new OptLogReqVO();
            vo1.setStatus(1);
            vo1.setOptType(6);
            vo1.setOptModule(3);
            String a="";
            for (LabelReqVO l : vo) {
                a=a+l.getTagName()+" ";
            }
            vo1.setOptContent("添加标签【"+a+"】");
            logService.saveOptLog(vo1);
            
        }
        if(vo.get(0).getDataType() == 5){
            List<String> collect = vo.stream().map(v -> v.getTagName()).collect(Collectors.toList());
            String url = elkUrl+indexName+"/_update_by_update";
            JSONObject params = new JSONObject();
            JSONObject f = new JSONObject();
            f.put("iir.iir_mysql_id",Long.parseLong(vo.get(0).getDataId()));
            JSONObject m = new JSONObject();
            m.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
            JSONObject source = new JSONObject();
            source.put("source","ctx._source.iir['iir_self_tag'] = '"+collect+"'");
            MyHttpClient client = new MyHttpClient();
            params.put("query",m);
            params.put("script",source);
            client.postJson(url,params);
        }
        
        
        TagRel tr = new TagRel();
        tr.setDataId(vo.get(0).getDataId());
        tr.setDataType(vo.get(0).getDataType());
        tagRelService.deleteByTagRel(tr);
        for (LabelReqVO labelReqVO : voList) {
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            TagRel tagRel = new TagRel();
            BeanUtils.copyProperties(labelReqVO,tagRel);
            tagRel.setStatus(Constant.DEFAULT_STATUS_NORMAL);
            tagRel.setId(myIdGenerator.nextId());
            tagRel.setCreateTime(new Date());
            tagRel.setCreateUserId(loginUser.getId());
            tagRel.setUpdateTime(new Date());
            tagRel.setUpdateUserId(loginUser.getId());
            tagRelService.add(tagRel);
        }
        
        return new ResponseInfo<>();
    }
    
}
